package com.aaa.arouterone.testlivedata

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.lifecycle.LiveData

/**
 * @Description:
 * @Author:  lfc
 * @Email:    iamlifuchang@163.com
 * @CreateTime:     2021/3/31 10:51
 * @UpdateRemark: 电量观察 livedata
 * todo  后期要考虑如何换成  hilt
 */
class BatteryLiveData constructor(var ctx: Context) : LiveData<Int>() {

    private var receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            value = intent?.getIntExtra("level", 0)
        }
    }

//    当LiveData绑定有活跃状态的observer时就会调用，在这里回去注册广播获得电池电量变化。

    override fun onActive() {
        super.onActive()
        var filter = IntentFilter()
        filter.addAction(Intent.ACTION_BATTERY_CHANGED)
        ctx.registerReceiver(receiver, filter)
    }

    override fun onInactive() {
        super.onInactive()
        ctx.unregisterReceiver(receiver)

    }

}